<?php
namespace Home\Controller;
use Think\Controller;
class OrderController extends Controller {
    private $admin_openid='oB_KewRQprjKA4ETYbqcRQgMiBk0';
    private $access_token='';
    public function index(){
    	// 设置选项，包括URL
    	$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . appid . "&redirect_uri=http://nuower.com/index.php/Order/oauth&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    	header("Location:".$url);
    }
    public function oauth() {
    	if (isset ( $_GET ['code'] )) {
    		$code = $_GET ['code'];
    		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . appid . "&secret=" . appsecret . "&code=" . $code . "&grant_type=authorization_code";
    		$output = https_request ( $url );
    		// 第二步
    		if (isset ( $output )) {
    			$jsoninfo = json_decode ( $output, true );
                session(array('expire'=>$jsoninfo['expires_in']));
                session('access_token',$jsoninfo['access_token']);

    			$url_info = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $jsoninfo ['access_token'] . "&openid=" . appid . "&lang=zh_CN";
    			$userInfo = https_request ( $url_info );
    		} else {
    			$this->error ( "不好意思,出错了" );
    		}
    		// 第三步
    		if (isset ( $userInfo )) {
    			$res = json_decode ( $userInfo, true );
    			cookie( "openid", $res ['openid'] );
                cookie( "nickname", $res ['nickname'] );
    			cookie( "headimgurl", $res ['headimgurl'] );
    			$this->select();
    		} else {
    			$this->error ( "不好意思,出错了" );
    		}
    	} else {
    		$this->error ( "不好意思,出错了" );
    	}
    }
    public function select(){
    	$where = array (
                "openid" => $_COOKIE['openid']
    	);

        /*$where = array (
                "openid" => 'oB_Kewa9G5LMhGzLCpQKePUz7EkA'
        );*/
    	$resE = M("order")->where($where)->where('status>=1')->field('id,getcity,startadd,endadd,orderno,ctime,time,car,status')->select();
        $resC = M("orders")->where($where)->where('status>=1')->field('id,getcity,startadd,endadd,orderno,ctime,time,car,status')->select();
    	$resP = M("order_p")->where($where)->field('id,getcity,startadd,endadd,orderno,ctime,time,car,status')->select();

        foreach ($resE as $key => $value) {
           $tmp =preg_replace('/\D/s', '', $value['time']);
            $f_time=substr($tmp, 0,12);
           $f_time= date("Y/m/d h:i",strtotime($f_time));
           $f_time= strtotime($f_time);
           $cur_time=time();
           if ($cur_time>$f_time) {
            $data['id']=$value['id'];
            $data['status']=1;
                M("order")->save($data);
           }
           $resE[$key]['is_carry']='不需要'; 

        }

        foreach ($resC as $key => $value) {
           $tmp =preg_replace('/\D/s', '', $value['time']);
            $f_time=substr($tmp, 0,12);
           $f_time= date("Y/m/d h:i",strtotime($f_time));
           $f_time= strtotime($f_time);
           $cur_time=time();
           if ($cur_time>$f_time) {
            $data['id']=$value['id'];
            $data['status']=1;
                M("orders")->save($data);
           }
           $resC[$key]['is_carry']='需要'; 
        }

        foreach ($resP as $key => $value) {
           $tmp =preg_replace('/\D/s', '', $value['time']);
            $f_time=substr($tmp, 0,12);
           $f_time= date("Y/m/d h:i",strtotime($f_time));
           $f_time= strtotime($f_time);
           $cur_time=time();
           if ($cur_time>$f_time) {
            $data['id']=$value['id'];
            $data['status']=1;
                M("order_p")->save($data);
           }
           $resP[$key]['is_carry']='专业搬家'; 

        }


        $res = array_merge($resE,$resC,$resP);
        /*foreach ($res as $key => $value) {
            $c = substr($value['orderno'],0,1);
            if ($c='E') {
              $res[$key]['is_carry']='不需要'; 
            }elseif ($c='C') {
              $res[$key]['is_carry']='需要'; 
            }else{
               $res[$key]['is_carry']='专业搬家'; 
            }

        }*/
        $this->assign("order",$res);
        $this->display("select");
    }

    public function delOrder(){
    	$orderno =  I("orderno");
    	$res = substr($orderno,0,1);
    	$tpl = $_SESSION['nickname']."取消订单了"."单号为:". $orderno;
    	//如果是E单，去order表中去删除订单
    	$where = array (
    			//"openid" => $_SESSION['openid'],
    			"orderno" => $orderno
    	);
    	//-1代表以删除订单
    	$status['status'] = '-1';
    	if($res=="E"){
    		$save = M ( 'order' )->where ( $where )->save($status); // 删除用户数据
    		//如果删除成功发送邮箱
    		if($save){
    			/*if (SendMail ( 'wxd1277@163.com', '亲，有人取消订单了！！', $tpl )) {
    				$this->success("取消订单成功",U ( 'Order/select' ));	
    			} else {
    				$this->error ( "取消失败",U ( 'Order/select' ) );
    			}*/
                $this->sendtpl_msg($this->admin_openid,$orderno,$tpl);
                echo "1";
    		}else{
    			$this->error("取消失败",U ( 'Order/select' ));
    		}
    	}else if($res=="C"){

    		$save = M ('orders')->where ($where)->save($status); // 删除用户数据
    		//如果删除成功发送邮箱
    		if($save){
    			
                 $this->sendtpl_msg($this->admin_openid,$orderno,$tpl);
                     echo "1";
                 //$this->success("取消订单成功",U ( 'Order/select' ));
    		}else{
    			$this->error("取消失败",U ( 'Order/select' ));
    		}
    	}
    }

    public function detail()
    {   
        $id=I('get.id');
        $orderinfo = M ( 'orders' )->find($id);
        $this->assign ( "orderinfo", $orderinfo);
        $this->display();
    }

    public function showcarry()
    {   
        $orderno=I('get.orderno');

        $res = substr($orderno,0,1);
        $where['orderno']=$orderno;
        if($res=="E"){
            $orderinfo = M ( 'order' )->where ( $where )->find(); 
            $this->assign ( "title",'小型搬家-不需要搬运');
             $this->assign ( "orderinfo",$orderinfo);
        $this->display();
           
        }else if($res=="C"){
            //如果是E单，去orders表中去删除订单
            $orderinfo = M ( 'orders' )->where ( $where )->find();
             $this->assign ( "title",'小型搬家-需要搬运');
              $this->assign ( "orderinfo",$orderinfo);
        $this->display();
        }else{
            $orderinfo = M ( 'order_p' )->where ( $where )->find();

            $jiaju=$orderinfo['items'];
    $jiajudata = explode('、',$jiaju);
        for ($i=0;$i<count($jiajudata)-1;$i++){ 
            $tmp=explode(' ', $jiajudata[$i]);
            $list[] = array(
                'name'=>$tmp[0],
                'num'=>$tmp[1],
            );
        }   $this->assign ( "list", $list);
            $this->assign ( "title",'专业搬家');
            $this->assign ( "orderinfo",$orderinfo);
            $this->display('showpo');
        }
       
    }


    public function pinglun()
    {   
        
          if(!IS_POST){
            $id=I('get.id');
        $type=I('get.type');
        switch ($type) {
        case 'carry':
        $M=M('orders');
            break;
        case 'nocarry':
         $M=M('order');
            break;
        case 'pro':
          $M=M('order_p');
            break;
        
        default:
           $M=M('orders');
            break;
    }   
            


        $orderinfo=$M->find($id);
        $this->assign('orderinfo',$orderinfo);
        $this->display();


          }else{
            $data=$_POST;
            switch ($data['type']) {
        case 'carry':
        $M=M('orders');
            break;
        case 'nocarry':
         $M=M('order');
            break;
        case 'pro':
          $M=M('order_p');
            break;
        
        default:
            # code...
            break;
    }   

            $pl['id']=$data['id'];
            $pl['headimgurl']=$_COOKIE['headimgurl'];
            $pl['pl_desc']=$data['comment'];
            $pl['pinglunstatus']=1;

           $r= $M->save($pl);
           if ($r) {
               $this->success('评论成功',U('Order/select'));
           }

          }
    }

    //发送模板消息 订单号
    public function sendtpl_msg($touser,$orderno,$first=''){

            $this->access_token=$this->getToken();
        $res = substr($orderno,0,1);
        $where['orderno']=$orderno;
        if($res=="E"){
            $orderinfo = M ( 'order' )->where ( $where )->find(); 
        }else if($res=="C"){
            $orderinfo = M ( 'orders' )->where ( $where )->find();
        }
    $cost=$orderinfo['cost'];
//模板消息  
$template=array(
'touser'=>$touser,
'template_id'=>"GrY-eEigqO2iMVwpm4KfO9G8N3FEYx_m004HMD68hXc",
'url'=>"http://nuower.com/index.php/Order/showcarry/orderno/".$orderno,
'topcolor'=>"#7B68EE",
'data'=>array(
'first'=>array('value'=>urlencode($first),'color'=>"#743A3A"),
'orderno'=>array('value'=>urlencode($orderno),'color'=>'#743A3A'),
'amount'=>array('value'=>urlencode($cost),'color'=>'#743A3A'),
'remark'=>array('value'=>urlencode('请查看'),'color'=>'#743A3A'),
)
);

$cus_user=$orderinfo['openid'];

    $content='您已取消订单';

$data = '{
        "touser":"'.$cus_user.'",
        "msgtype":"text",
        "text":
        {
             "content":"'.$content.'"
        }
    }';


$json_template=json_encode($template);

$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$url2 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
$res=http_request($url,urldecode($json_template));
$res2=https_post($url2,urldecode($data));

}

public function getToken()
{   
    $data = json_decode(get_php_file("access_token.php"));
    if ($data->expire_time < time()) {
       $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".appid."&secret=".appsecret);
$access_token=json_decode($json_token,true);
//获得access_token
$this->access_token=$access_token['access_token'];
      if ($this->access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
      set_php_file("access_token.php", json_encode($data));
      }
    } else {

     $this->access_token = $data->access_token->access_token;
    }
    return $this->access_token;
    
}

public function pl_list()
{   
    $map['pinglunstatus']=1;
    $p_plist=M('order_p')->where($map)->field('orderno,pl_desc,headimgurl,user_nickname,pl_addtime,score')->select();
    $e_plist=M('order')->where($map)->field('orderno,pl_desc,headimgurl,user_nickname,pl_addtime,score')->select();
    $c_plist=M('orders')->where($map)->field('orderno,pl_desc,headimgurl,user_nickname,pl_addtime,score')->select();

    $list=array_merge($p_plist,$e_plist,$c_plist);

    $this->assign('list',$list);
   $this->display();

}

public function showpic(){

        $id=I('id');
        if ($id){
            $list=M('order_p')->where(array('id'=>$id))->field('otherimages')->find();
            $orderno=M('order_p')->where(array('id'=>$id))->field('orderno')->find();
             $file_name=$orderno['orderno'].'.zip';

           $list=unserialize($list['otherimages']);
                foreach ($list as $key => $value) {
                    $img_file=__ROOT__."/Uploads/weixin/".$value.'.jpg';
                    $imglist[]=$img_file;
                }
             $this->assign('imglist',$imglist);
   $this->display();
            
        }

    }
        


    
}